﻿using StardewModdingAPI;
using StardewModdingAPI.Events;
using StardewValley;
using StardewValley.Monsters;
using WorseGame.Content.怪物增强;

namespace WorseGame.Content
{
    public class 怪物加强系统(IMonitor monitor, IModHelper helper)
    {
        private readonly IMonitor 监视器 = monitor;
        private readonly IModHelper 助手 = helper;
        private readonly Dictionary<Type, 怪物增强器> 怪物增强器列表 = [];

        public void Initialize()
        {
            初始化增强器();
            助手.Events.GameLoop.UpdateTicked += 更新怪物;
            助手.Events.GameLoop.DayStarted += 每天重置;
        }

        private void 初始化增强器()
        {
            怪物增强器列表.Add(typeof(GreenSlime), new 史莱姆增强器());     
            怪物增强器列表.Add(typeof(Grub), new 臭虫增强器());           
        }

        private void 更新怪物(object? sender, UpdateTickedEventArgs e)
        {
            if (Context.IsWorldReady)
            {
                foreach (var location in Game1.locations)
                {
                    foreach (var monster in location.characters)
                    {
                        if (monster is Monster 怪物)
                        {
                            应用怪物增强(怪物);
                        }
                    }
                }
            }
        }

        private void 应用怪物增强(Monster 怪物)
        {
            Type 怪物类型 = 怪物.GetType();
            if (怪物增强器列表.TryGetValue(怪物类型, out 怪物增强器? value))
            {
                value.应用增强(怪物);
            }
        }

        private void 每天重置(object? sender, DayStartedEventArgs e)
        {
            foreach (var 增强器 in 怪物增强器列表.Values)
            {
                增强器.重置();
            }
        }
    }

    public abstract class 怪物增强器
    {
        public virtual void 应用增强(Monster 怪物)
        {
            float 难度系数 = 计算难度系数();
            怪物.MaxHealth = (int)(怪物.MaxHealth * 难度系数);
            if (怪物.Health > 0)
            {
                怪物.Health = (int)(怪物.Health * 难度系数);
            }
            怪物.DamageToFarmer = (int)(怪物.DamageToFarmer * 难度系数);
            怪物.resilience.Value = (int)(怪物.resilience.Value * 难度系数);
        }

        protected virtual float 计算难度系数()
        {
            float 年份加成 = 1 + (Game1.year - 1) * 0.2f;
            float 矿井加成 = 1 + (Game1.player.deepestMineLevel / 120f) * 0.5f;
            return 年份加成 * 矿井加成;
        }

        public virtual void 重置()
        {
        }
    }
}
